package com.hl.vcd.controller;

import com.hl.common.result.R;
import com.hl.common.result.ResponseEnum;
import com.hl.common.utils.JwtUtils;
import com.hl.common.utils.OssUtils;
import com.hl.vcd.entity.User;
import com.hl.vcd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱炫达
 */
@RestController
@RequestMapping("/api/core")
public class UserController {

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String,String> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    private String getUserIdByHeaderMap(Map<Object,Object> map){
        String uuidToken = map.get("authorization").toString();
        String uuid = JwtUtils.getUUIDByJwtToken(uuidToken);
        String loginToken = redisTemplate.opsForValue().get(uuid);
        return JwtUtils.getMemberIdByJwtToken(loginToken);
    }

    @PostMapping("/add_user/{code}")
    public R addUser(@RequestBody User user,@PathVariable String code) {
        User userSelect = userService.getUserByMail(user.getMail());
        if(userSelect != null){
            return R.error().message("用户已存在");
        }
        String codeFromRedis = redisTemplate.opsForValue().get(user.getMail());
        if(codeFromRedis != null && codeFromRedis.equals(code)){
            userService.addUser(user);
            return R.ok();
        }
        else{
            return R.setResult(ResponseEnum.CODE_ERROR);
        }
    }

    @GetMapping("/select_user_by_mail/{mail}")
    public boolean selectUserByMail(@PathVariable String mail) {
        User user = userService.getUserByMail(mail);
        return user != null;
    }

    @PostMapping("/user_login")
    public R userLogin(@RequestBody User user){
        User userSelect = userService.selectUserByMailAndPassword(user.getMail(),user.getPassword());
        String uuid = String.valueOf(UUID.randomUUID());
        if (userSelect == null){
            return R.error().message("账号密码错误");
        }

        String UUIDToken = JwtUtils.getJwtToken(uuid);
        String loginToken = JwtUtils.getJwtToken(userSelect.getId(),userSelect.getMail());
        redisTemplate.opsForValue().set(uuid,loginToken,7, TimeUnit.DAYS);

        userSelect.setPassword(null);
        Map<Object,Object> map = new HashMap<Object,Object>(){};
        map.put("authorization",UUIDToken);
        map.put("user",userSelect);
        return R.ok().message("登录成功").data(map);
    }

    @GetMapping("/user_logout")
    public R userLogout(@RequestHeader Map<Object,Object> map){
        String uuidToken = map.get("authorization").toString();
        String uuid = JwtUtils.getUUIDByJwtToken(uuidToken);
        redisTemplate.delete(uuid);
        return R.ok().message("登出成功");
    }

    @GetMapping("/get_user_info")
    public R getUserInfo(@RequestHeader Map<Object,Object> map){
        String userId = getUserIdByHeaderMap(map);

        User user = userService.getUserById(userId);
        user.setPassword("");

        return R.ok().message("获取用户信息成功").data("userInfo",user);
    }

    @PutMapping("/update_user_info")
    public R updateUserInfo(@RequestHeader Map<Object,Object> map, @RequestBody User user){
        String userId = getUserIdByHeaderMap(map);

        user.setId(userId).setMail(null).setPassword(null).setIsDeleted(null).setGmtCreate(null).setGmtModified(null);
        userService.updateUser(user);

        return R.ok().message("更新用户信息成功");
    }

    @GetMapping("/check_update_password_code/{code}")
    public R checkUpdatePasswordCode(@RequestHeader Map<Object,Object> map, @PathVariable String code){
        String userId = getUserIdByHeaderMap(map);

        String codeFromRedis = redisTemplate.opsForValue().get(userId+"UpdatePasswordEmail");
        if(codeFromRedis != null && codeFromRedis.equals(code)){
            return R.ok().message("验证码有效");
        }
        else{
            return R.setResult(ResponseEnum.CODE_ERROR);
        }
    }

    @PutMapping("/update_password/{code}")
    public R updatePassword(@RequestHeader Map<Object,Object> map, @PathVariable String code, @RequestBody String password){
        String userId = getUserIdByHeaderMap(map);

        String codeFromRedis = redisTemplate.opsForValue().get(userId+"UpdatePasswordEmail");
        if(codeFromRedis != null && codeFromRedis.equals(code)){
            User userUpdate = new User();
            userUpdate.setId(userId).setPassword(password);
            userService.updateUser(userUpdate);
            return R.ok().message("更新密码成功");
        }
        else{
            return R.error().message("验证码已过期");
        }
    }

    @PutMapping("/update_avatar")
    public R updateAvatar(@RequestHeader Map<Object,Object> map, @RequestParam("avatar") MultipartFile avatarFile){
        String userId = getUserIdByHeaderMap(map);

        User user = userService.getUserById(userId);
        if (user.getAvatarUrl() != null){
            OssUtils.deleteFile(user.getAvatarUrl());
        }

        boolean result = userService.uploadUserAvatarById(avatarFile,userId);
        if (result){
            return R.ok().message("更新头像成功");
        }
        else {
            return R.error().message("更新头像失败");
        }
    }

}
